﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Linq;
using DienThoai.CONTROLLERS;
using DienThoai.MODELS;



namespace DienThoai
{
	/// <summary>
	/// Interaction logic for Manager.xaml
	/// </summary>
	public partial class Manager : Window
	{
        private ManagerModel.DeletePhoneEventHandler DeletePhoneDelegate;
        
        DienThoaiDataContext db = new DienThoaiDataContext();
        public string UserName;
		public Manager()
		{
			this.InitializeComponent();
            HandleEvent();
            // Insert code required on object creation below this point.
		}

        private void HandleEvent()
        {
            DeletePhoneDelegate = new ManagerModel.DeletePhoneEventHandler(DeletePhoneCompleted);
            ManagerModel.Instance.DeletePhoneEvent += DeletePhoneDelegate;
        }

        private void DeletePhoneCompleted(object sender, EventArgs e)
        {
            btPhoneFinding_Click(this, null);
            MessageBox.Show("Xóa sản phẩm thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btNewCustomer_Click(object sender, RoutedEventArgs e)
        {
            CustomerInfoxaml formCustomerInfo = new CustomerInfoxaml();
            formCustomerInfo.ShowDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Utility utility = new Utility();
            lbUsername.Content = UserName;
            lbToday.Content = ","+DateTime.Today.ToString();
            utility.getCustomerDataGrid(dgCustomers);
            utility.getStaffDataGrid(dgStaff);
            //combobox năm
            for (int i = 0; i < 30; i++)
            {
                cbbYear.Items.Add(DateTime.Now.Year - i);
            }
            for (int i = 0; i < 30; i++)
            {
                
                cbbYearGraph.Items.Add(DateTime.Now.Year - i);
            }
            //tab Nhân Viên
            var Roles = from i in db.Roles
                        select i.RoleName;
            foreach (var role in Roles)
                cbbRole.Items.Add(role);
            //tab Phone
            var Manufacturer = from i in db.Manufacrurers
                               select i.ManufacrurerName;
            foreach (var i in Manufacturer)
            {
                cbbManufacturer.Items.Add(i);
                cbbAccessoryManufacturer.Items.Add(i);
            }
            var CameraPixel = from i in db.CameraDetails
                              select i.MegaPixel;
            foreach (var i in CameraPixel)
                cbbCamera.Items.Add(i);

            var sim = from i in db.MultiSims
                      select i.SimQuantity;
            foreach (var i in sim)
                cbbMultiSim.Items.Add(i);

            var TouchScreen = from i in db.TouchScreenDetails
                      select i.Point;
            foreach (var i in TouchScreen)
                cbbTouchScreen.Items.Add(i);

            var memory = from i in db.MemoryCards
                         select i.Size;
            foreach (var i in memory)
                cbbMemoryCard.Items.Add(i);
            if (cbbMemoryCard.Items.Count > 0)
            {
                cbbMemoryCard.SelectedIndex = 0;
            }
            if (cbbMultiSim.Items.Count > 0)
            {
                cbbMultiSim.SelectedIndex = 0;
            }
            if (cbbTouchScreen.Items.Count > 0)
            {
                cbbTouchScreen.SelectedIndex = 0;
            }
            if (cbbCamera.Items.Count > 0)
            {
                cbbCamera.SelectedIndex = 0;
            }
            //tab Accessory
            var accessoryKind = from i in db.AccessoryKinds
                                select i.Name;
            foreach (var i in accessoryKind)
                cbbAccessoryKind.Items.Add(i);
            //Graph
            cbbYearGraph.SelectedIndex = 0;
            //tab Thay doi quy dinh
            var query1 = from t in db.CameraDetails
                         select t.MegaPixel.ToString();
            foreach (var item in query1)
            {
                cbCamera.Items.Add(item);
            }
            var query = from t in db.MemoryCards
                        select t.Size;
            foreach (var item in query)
            {
                cbTheNho.Items.Add(item);
            }
            var query2 = from t in db.MultiSims
                         select t.SimQuantity.ToString();
            foreach (var item in query2)
            {
                cbSim.Items.Add(item);
            }
            var query3 = from t in db.Manufacrurers
                    select t.ManufacrurerName;
            foreach (var item in query3)
            {
                cbNhaSanXuat.Items.Add(item);
            }
            var query4 = from t in db.Suppliers
                    select t.Name;
            foreach (var item in query4)
            {
                cbNhaPhanPhoi.Items.Add(item);
            }
        }
        private void Window_Activated(object sender, EventArgs e)
        {
            Utility u = new Utility();
            u.getCustomerDataGrid(dgCustomers);
            u.getStaffDataGrid(dgStaff);
        }

        private void btEdit_Click(object sender, RoutedEventArgs e)
        {
            Customer selected = dgCustomers.SelectedItem as Customer;
            if (selected == null)
                MessageBox.Show("Bạn chưa chọn khách hàng cần sửa đổi.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
            else
            {
                UpdateCustomer f = new UpdateCustomer(selected);
                f.ShowDialog();
            }
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            Utility u = new Utility();
            u.getCustomerDataGrid(dgCustomers);
            u.getStaffDataGrid(dgStaff);
        }

        private void btDelete_Click(object sender, RoutedEventArgs e)
        {
            Utility utility = new Utility();
            Customer deleteCustomer = dgCustomers.SelectedItem as Customer;
            //xóa trong customer
            var qDelCustomer = from i in db.Customers
                               where i.PersonID == deleteCustomer.PersonID
                               select i;
            foreach (var customer in qDelCustomer)
                db.Customers.DeleteOnSubmit(customer);
            //xóa trong Person
            var qDelPerson = from i in db.Persons
                             where i.PersonID == deleteCustomer.PersonID
                             select i;
            foreach (var customer in qDelPerson)
                db.Persons.DeleteOnSubmit(customer);
            db.SubmitChanges();
            MessageBox.Show("Xóa khách hàng " + deleteCustomer.Person.Fullname + " thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void btFinding_Click(object sender, RoutedEventArgs e)
        {
            
            Utility u = new Utility();
            if (txtFinding.Text == "" && cbbYear.SelectedValue == null)
                u.getCustomerDataGrid(dgCustomers);
            else if(txtFinding.Text == "" && cbbYear.SelectedValue != null)
                u.getCustomerDataGrid(dgCustomers,int.Parse(cbbYear.SelectedValue.ToString()));
            else if(txtFinding.Text !="" && cbbYear.SelectedValue ==null)
                u.getCustomerDataGrid(dgCustomers, txtFinding.Text);
            else
                u.getCustomerDataGrid(dgCustomers,txtFinding.Text,int.Parse(cbbYear.SelectedValue.ToString()));

            cbbYear.SelectedValue = "";
        }

        private void btCreateNewStaff_Click(object sender, RoutedEventArgs e)
        {
            StaffControl f = new StaffControl();
            f.ShowDialog();
        }

        private void btEditStaff_Click(object sender, RoutedEventArgs e)
        {
            Staff staff = dgStaff.SelectedItem as Staff;
            UpdateStaff f;
            if (staff == null)
                MessageBox.Show("Chưa chọn nhân viên cần sửa.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
            else
            {
                f = new UpdateStaff(staff);
                f.ShowDialog();
            }
        }

        private void btDelStaff_Click(object sender, RoutedEventArgs e)
        {
            Staff delete = dgStaff.SelectedItem as Staff;
            var deleteStaff = from i in db.Staffs
                              where i.PersonID == delete.PersonID
                              select i;
            var deletePerson = from i in db.Persons
                               where i.PersonID == delete.PersonID
                               select i;
            foreach(var staff in deleteStaff)
                db.Staffs.DeleteOnSubmit(staff);
            foreach (var person in deletePerson)
                db.Persons.DeleteOnSubmit(person);
            db.SubmitChanges();
            MessageBox.Show("Xóa nhân viên" + delete.Username + " thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);

        }

        private void btStaffFinding_Click(object sender, RoutedEventArgs e)
        {
            Utility u = new Utility();
            if (txtStaffFinding.Text == "" && cbbRole.SelectedValue == null)
                u.getStaffDataGrid(dgStaff);
            else if (txtStaffFinding.Text == "" && cbbRole.SelectedValue != null)
            {
                u.getStaffDataGrid(dgStaff, cbbRole.SelectedValue.ToString());
            }
            else if (txtStaffFinding.Text != "" && cbbRole.SelectedValue == null)
            {
                u.getStaffDataGrid(dgStaff, rbUsername, rbName, txtStaffFinding.Text);
            }
            else
                u.getStaffDataGrid(dgStaff, cbbRole.SelectedValue.ToString(), rbUsername, rbName, txtStaffFinding.Text);

            cbbRole.SelectedValue = "";
        }
//tab Phone !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        private void btPhoneFinding_Click(object sender, RoutedEventArgs e)
        {
            Utility u = new Utility();
            if (txtPhoneFinding.Text == "")
                u.Manager_getPhoneDataGrid(dgPhone);
            else
                u.Manager_getPhoneDataGrid(dgPhone, txtPhoneFinding.Text);
        }

        private void dgPhone_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Phone selectedPhone = dgPhone.SelectedItem as Phone;
            if (selectedPhone != null)
            {
                lbMaSP.Content = selectedPhone.PhoneID;
                cbbManufacturer.SelectedValue = selectedPhone.Product.Manufacrurer.ManufacrurerName;
                txtPhoneModel.Text = selectedPhone.Product.Model;
                if (selectedPhone.Product.Quantity == 0)
                    lbPhoneQuantity.Content = "Hết";
                else
                    lbPhoneQuantity.Content = "Còn";
                txtPhonePrice.Text = selectedPhone.Product.Price.ToString();
                if (selectedPhone.Music == true)
                    cbMp3Player.IsChecked = true;
                else
                    cbMp3Player.IsChecked = false;

                if (selectedPhone.TV == true)
                    cbTV.IsChecked = true;
                else
                    cbTV.IsChecked = false;

                if (selectedPhone.BlueTooth == true)
                    cbBluetooth.IsChecked = true;
                else
                    cbBluetooth.IsChecked = false;

                if (selectedPhone.Wifi == true)
                    cbWifi.IsChecked = true;
                else
                    cbWifi.IsChecked = false;

                if (selectedPhone.FMRadio == true)
                    cbFM.IsChecked = true;
                else
                    cbFM.IsChecked = false;

                if (selectedPhone.VoiceRecord == true)
                    cbRecording.IsChecked = true;
                else
                    cbRecording.IsChecked = false;

                if (selectedPhone.QWERTY == true)
                    cbQwerty.IsChecked = true;
                else
                    cbQwerty.IsChecked = false;

                if (selectedPhone.GPS == true)
                    cbGPS.IsChecked = true;
                else
                    cbGPS.IsChecked = false;

                if (selectedPhone.CameraDetailID == null)
                    cbbCamera.SelectedValue = 0;
                else
                {
                    cbbCamera.SelectedValue = selectedPhone.CameraDetail.MegaPixel;
                }
                if (selectedPhone.TouchScreenDetailID != null)
                    cbbTouchScreen.SelectedValue = selectedPhone.TouchScreenDetail.Point;
                else
                    cbbTouchScreen.SelectedValue = null;
                if (selectedPhone.MultiSimID != null)
                    cbbMultiSim.SelectedValue = selectedPhone.MultiSim.SimQuantity;
                else
                    cbbMultiSim.SelectedValue = null;
            }
        }

        private void btPhoneEdit_Click(object sender, RoutedEventArgs e)
        {            
            Phone selectedPhone = dgPhone.SelectedItem as Phone;
            if (dgPhone.SelectedItem == null)
                MessageBox.Show("Chưa chọn sản phẩm cần sửa.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Information);
            else
            {
                var editedPhone = from i in db.Phones
                                  where i.PhoneID == selectedPhone.PhoneID
                                  select i;
                foreach (var i in editedPhone)
                {
                    var manufacturer = from j in db.Manufacrurers
                                       where j.ManufacrurerName == cbbManufacturer.SelectedValue.ToString()
                                       select j.ManufacrurerID;
                    foreach (var j in manufacturer)
                    {
                        i.Product.ManufacturerID = j;
                        selectedPhone.Product.ManufacturerID = j;
                    }
                    i.Product.Model = txtPhoneModel.Text;
                    selectedPhone.Product.Model = txtPhoneModel.Text;
                    i.Product.Price = float.Parse(txtPhonePrice.Text);

                    var multiSim = from j in db.MultiSims
                                   where j.SimQuantity.ToString() == cbbMultiSim.SelectedValue.ToString()
                                   select j.MultiSimID;
                    foreach (var j in multiSim)
                        i.MultiSimID = j;

                    var touchScreen = from j in db.TouchScreenDetails
                                      where j.Point == cbbTouchScreen.SelectedValue.ToString()
                                      select j.TouchScreenDetailID;
                    foreach (var j in touchScreen)
                        i.TouchScreenDetailID = j;

                    if (cbMp3Player.IsChecked == true)
                        i.Music = true;
                    else
                        i.Music = false;

                    if (cbTV.IsChecked == true)
                        i.TV = true;
                    else
                        i.TV = false;

                    if (cbBluetooth.IsChecked == true)
                        i.BlueTooth = true;
                    else
                        i.BlueTooth = false;

                    if (cbWifi.IsChecked == true)
                        i.Wifi = true;
                    else
                        i.Wifi = false;

                    if (cbFM.IsChecked == true)
                        i.FMRadio = true;
                    else
                        i.FMRadio = false;

                    if (cbRecording.IsChecked == true)
                        i.VoiceRecord = true;
                    else
                        i.VoiceRecord = false;

                    if (cbQwerty.IsChecked == true)
                        i.QWERTY = true;
                    else
                        i.QWERTY = false;

                    if (cbGPS.IsChecked == true)
                        i.GPS = true;
                    else
                        i.GPS = false;

                    var camera = from j in db.CameraDetails
                                 where j.MegaPixel == cbbCamera.SelectedValue.ToString()
                                 select j.CameraDetailID;
                    foreach (var j in camera)
                    {
                        i.CameraDetailID = j;
                    }


                    var conflictModel = from j in db.Products
                                        where j.ManufacturerID == i.Product.ManufacturerID && i.Product.Model == j.Model && i.PhoneID != j.ProductID
                                        select i;
                    if (txtPhoneModel.Text == "")
                        MessageBox.Show("Chưa nhập tên cho sản phẩm.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                    else if (conflictModel.Count() != 0)
                        MessageBox.Show("Mặt hàng đã tồn tại trong cơ sở dữ liệu.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    else
                    {
                        db.SubmitChanges();
                        MessageBox.Show("Sửa sản phẩm thành công!", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }             
        }

        private void cbNewPhone_Checked(object sender, RoutedEventArgs e)
        {

            spPhoneFinding.IsEnabled = false;
            btNewPhone.IsEnabled = true;
            btPhoneEdit.IsEnabled = false;
            btPhoneDelete.IsEnabled = false;
        }

        private void cbNewPhone_Unchecked(object sender, RoutedEventArgs e)
        {
            spPhoneFinding.IsEnabled = true;
            btNewPhone.IsEnabled = false;
            btPhoneEdit.IsEnabled = true;
            btPhoneDelete.IsEnabled = true;
        }

        private void btNewPhone_Click(object sender, RoutedEventArgs e)
        {
            db = new DienThoaiDataContext();
            Product newProduct = new Product();
            Phone newPhone = new Phone();
            newProduct.ProductID = getID();

            var manufacturer = from i in db.Manufacrurers
                               where i.ManufacrurerName == cbbManufacturer.SelectedValue.ToString()
                               select i.ManufacrurerID;
            foreach (var i in manufacturer)
                newProduct.ManufacturerID = i;
            newProduct.Model = txtPhoneModel.Text;
            newProduct.Quantity = 0;
            newProduct.Price = float.Parse(txtPhonePrice.Text);
            
            
            newPhone.PhoneID = newProduct.ProductID;
            if (cbMp3Player.IsChecked == true)
                newPhone.Music = true;
            if (cbTV.IsChecked == true)
                newPhone.TV = true;
            if (cbBluetooth.IsChecked == true)
                newPhone.BlueTooth = true;
            if (cbWifi.IsChecked == true)
                newPhone.Wifi = true;
            if (cbFM.IsChecked == true)
                newPhone.FMRadio = true;
            if (cbRecording.IsChecked == true)
                newPhone.VoiceRecord = true;
            if (cbQwerty.IsChecked == true)
                newPhone.QWERTY = true;
            if (cbGPS.IsChecked == true)
                newPhone.GPS = true;

            var multiSim = from i in db.MultiSims
                          where i.SimQuantity.ToString() == cbbMultiSim.SelectedValue.ToString()
                          select i.MultiSimID;
            foreach (var i in multiSim)
                newPhone.MultiSimID = i;

            var touchScreen = from i in db.TouchScreenDetails
                              where i.Point == cbbTouchScreen.SelectedValue.ToString()
                              select i.TouchScreenDetailID;

            foreach (var i in touchScreen)
                newPhone.TouchScreenDetailID = i;

            var camera = from i in db.CameraDetails
                           where i.MegaPixel == cbbCamera.SelectedValue.ToString()
                           select i.CameraDetailID;

            foreach (var i in camera)
                newPhone.CameraDetailID = i;

            var memory = from i in db.MemoryCards
                         where i.Size == cbbMemoryCard.SelectedValue.ToString()
                         select i.MemoryCardID;
            foreach (var i in memory)
                newPhone.MemoryCardID = i;
            if (cbbManufacturer.SelectedValue == null)
            {
                MessageBox.Show("Chưa chọn hãng sản xuất", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else if (txtPhoneModel.Text == "")
                MessageBox.Show("Chưa chọn tên sản phẩm.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
            else
            {
                var conflictModel = from i in db.Products
                                    where i.ManufacturerID == newProduct.ManufacturerID && i.Model == newProduct.Model
                                    select i;
                if (conflictModel.Count() != 0)
                    MessageBox.Show("Măt hàng đã tồn tại trong CSDL.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                else
                {
                    db.Products.InsertOnSubmit(newProduct);
                    db.Phones.InsertOnSubmit(newPhone);
                    try
                    {
                        db.SubmitChanges();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    MessageBox.Show("Thêm sản phẩm thành công!", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            
        }
        private string getID()
        {
            string ID = "";

            var query = from i in db.Phones
                        select i.PhoneID;

            if (query.Count() == 0)
                ID = "P00001";
            else
            {
                int temp = 0;
                foreach (var i in query)
                    temp = int.Parse(i.ToString().Substring(2)) + 1;
                if (temp < 10)
                    ID = "P0000" + temp.ToString();
                else if (temp < 100)
                    ID = "P000" + temp.ToString();
                else if (temp < 1000)
                    ID = "P00" + temp.ToString();
                else if (temp < 10000)
                    ID = "P0" + temp.ToString();
                else
                    ID = "P" + temp.ToString();
            }
            return ID;
        }

        private void txtPhonePrice_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key >= Key.D0 && e.Key <= Key.D9)
            {
                if (txtPhonePrice.Text != "")                   
                        e.Handled = false;
            }
            else
                e.Handled = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btPhoneDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dgPhone.SelectedItem != null)
            {
                Phone selectedPhone = dgPhone.SelectedItem as Phone;                
                if (selectedPhone.Product.Quantity != 0)
                    MessageBox.Show("Sản phẩm hiện vẫn còn, chưa thể xóa được.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                else
                {
                    ManagerController.Instance.InvokeDeletePhone(selectedPhone);
                }
            }
        }
//Tab Accessory !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        private void btAccessoryFinding_Click(object sender, RoutedEventArgs e)
        {
            Utility u = new Utility();
            if (txtAccessoryFinding.Text == "")
                u.Manager_getAccessoryDataGrid(dgAccessory);
            else
                u.Manager_getAccessoryDataGrid(dgAccessory, txtAccessoryFinding.Text);
        }

        private void cbAccessoryNew_Checked(object sender, RoutedEventArgs e)
        {
            btAccessoryNew.IsEnabled = true;
            btAccessoryEdit.IsEnabled = false;
            btAccessoryDelete.IsEnabled = false;
            spAccessoryFinding.IsEnabled = false;
        }

        private void cbAccessoryNew_Unchecked(object sender, RoutedEventArgs e)
        {
            btAccessoryNew.IsEnabled = false;
            btAccessoryEdit.IsEnabled = true;
            btAccessoryDelete.IsEnabled = true;
            spAccessoryFinding.IsEnabled = true;
        }

        private void dgAccessory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {    
            Accessory selectedAccessory = dgAccessory.SelectedItem as Accessory;
            if (selectedAccessory != null)
            {
                cbbAccessoryManufacturer.SelectedValue = selectedAccessory.Product.Manufacrurer.ManufacrurerName;
                txtAccessoryModel.Text = selectedAccessory.Product.Model;
                txtAccessoryPrice.Text = selectedAccessory.Product.Price.ToString();
                cbbAccessoryKind.SelectedValue = selectedAccessory.AccessoryKind.Name;
                txtAccessoryDetail.Text = selectedAccessory.Detail;
            }
        }

        private void btAccessoryNew_Click(object sender, RoutedEventArgs e)
        {
            Product newProduct = new Product();
            Accessory newAccessory = new Accessory();
            newProduct.ProductID = getAccessoryID();
            var manufacturer = from i in db.Manufacrurers
                               where i.ManufacrurerName == cbbAccessoryManufacturer.SelectedValue.ToString()
                               select i.ManufacrurerID;

            var accessoryKind = from i in db.AccessoryKinds
                                where i.Name == cbbAccessoryKind.SelectedValue.ToString()
                                select i.AccessoryKindID;
            
            if (cbbAccessoryManufacturer.SelectedValue == null)
                MessageBox.Show("Chưa chọn nhà sản xuất", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
            else if (txtAccessoryModel.Text == "")
                MessageBox.Show("Chưa nhập tên phụ kiện", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
            else if (txtAccessoryPrice.Text == "")
                MessageBox.Show("Chưa nhập giá cho sản phẩm", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
            else if (cbbAccessoryKind.SelectedValue == null)
                MessageBox.Show("Chưa chọn loại phụ kiện.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
            else
            {
                
                //var conflictModel = from k in db.Accessories
                //                    where k.Product.Model == txtAccessoryModel.Text && k.Product.Manufacrurer.ManufacrurerName == cbbManufacturer.SelectedValue.ToString() && k.AccessoryKind.Name == cbbAccessoryKind.SelectedValue.ToString()
                //                    select k; 
                //if (conflictModel.Count() == 0)
                //    MessageBox.Show("Sản phẩm cùng nhà sản xuất và cùng loại phụ kiện. Xin nhập lại.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                //else
                {
                    foreach (var i in manufacturer)
                        newProduct.ManufacturerID = i;
                    newProduct.Model = txtAccessoryModel.Text;
                    newProduct.Quantity = 0;
                    newProduct.Price = float.Parse(txtAccessoryPrice.Text);

                    newAccessory.AccessoryID = newProduct.ProductID;
                    newAccessory.Detail = txtAccessoryDetail.Text;

                    foreach (var i in accessoryKind)
                        newAccessory.AccessoryKindID = i;

                    db.Products.InsertOnSubmit(newProduct);
                    db.Accessories.InsertOnSubmit(newAccessory);
                    db.SubmitChanges();

                    MessageBox.Show("Thêm phụ kiện thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }

        private string getAccessoryID()
        {
            string ID = "";

            var query = from i in db.Accessories
                        select i.AccessoryID;

            if (query.Count() == 0)
                ID = "PK00001";
            else
            {
                int temp = 0;
                foreach (var i in query)
                    temp = int.Parse(i.ToString().Substring(2)) + 1;
                if (temp < 10)
                    ID = "PK0000" + temp.ToString();
                else if (temp < 100)
                    ID = "PK000" + temp.ToString();
                else if (temp < 1000)
                    ID = "PK00" + temp.ToString();
                else if (temp < 10000)
                    ID = "PK0" + temp.ToString();
                else
                    ID = "PK" + temp.ToString();
            }
            return ID;
        }

        private void btAccessoryEdit_Click(object sender, RoutedEventArgs e)
        {
            Accessory selectedAccessory = dgAccessory.SelectedItem as Accessory;
            var editedAccessory = from i in db.Accessories
                                  where i.AccessoryID == selectedAccessory.AccessoryID
                                  select i;
            if (editedAccessory != null)
            {
                var manufacturer = from i in db.Manufacrurers
                                   where i.ManufacrurerName == cbbAccessoryManufacturer.SelectedValue.ToString()
                                   select i.ManufacrurerID;

                var accessoryKind = from i in db.AccessoryKinds
                                    where i.Name == cbbAccessoryKind.SelectedValue.ToString()
                                    select i.AccessoryKindID;
                if (txtAccessoryModel.Text == "")
                    MessageBox.Show("Chưa điền tên sản phẩm.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (txtAccessoryPrice.Text == "")
                    MessageBox.Show("Chưa điền giá sản phẩm.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    foreach (var k in editedAccessory)
                    {
                        foreach (var i in manufacturer)
                        {
                            k.Product.ManufacturerID = i;
                            selectedAccessory.Product.ManufacturerID = i;
                        }
                        foreach (var i in accessoryKind)
                        {
                            k.AccessoryKindID = i;
                            selectedAccessory.AccessoryKindID = i;
                        }
                        k.Product.Model = txtAccessoryModel.Text;
                        selectedAccessory.Product.Model = txtAccessoryModel.Text;
                        k.Product.Price = float.Parse(txtAccessoryPrice.Text);
                        k.Detail = txtAccessoryDetail.Text;

                        db.SubmitChanges();
                        MessageBox.Show("Cập nhật phụ kiện thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
        }

        private void txtAccessoryPrice_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key >= Key.D0 && e.Key <= Key.D9)
            {
                if (txtAccessoryPrice.Text != "")
                    e.Handled = false;
            }
            else
                e.Handled = true;
        }
// Đồ thị !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        private void btGraph_Click(object sender, RoutedEventArgs e)
        {
            Graph f = new Graph(int.Parse(cbbYearGraph.SelectedValue.ToString()));
            f.ShowDialog();
        }
       

        /// <summary>
        /// This method is used to getCameraDetailID
        /// </summary>
        /// <returns>CameraDetailID</returns>
        private string getCameraDetailID()
        {
            string ID = "";

            var query = from i in db.CameraDetails
                        select i.CameraDetailID;

            if (query.Count() == 0)
                ID = "C001";
            else
            {
                int temp = 0;
                foreach (var i in query)
                    temp = int.Parse(i.ToString().Substring(2)) + 1;
                if (temp < 10)
                    ID = "C00" + temp.ToString();
                else if (temp < 100)
                    ID = "C0" + temp.ToString();
                else
                    ID = "C" + temp.ToString();
            }
            return ID;
        }

        /// <summary>
        /// This method is used to getMemoryCardID
        /// </summary>
        /// <returns>MemoryCardID</returns>
        private string getMemoryCardID()
        {
            string ID = "";

            var query = from i in db.MemoryCards
                        select i.MemoryCardID;

            if (query.Count() == 0)
                ID = "MC001";
            else
            {
                int temp = 0;
                foreach (var i in query)
                    temp = int.Parse(i.ToString().Substring(2)) + 1;
                if (temp < 10)
                    ID = "MC00" + temp.ToString();
                else if (temp < 100)
                    ID = "MC0" + temp.ToString();
                else
                    ID = "MC" + temp.ToString();
            }
            return ID;
        }

        /// <summary>
        /// This method is used to getSimID
        /// </summary>
        /// <returns>SimID</returns>
        private string getSimID()
        {
            string ID = "";

            var query = from i in db.MultiSims
                        select i.MultiSimID;

            if (query.Count() == 0)
                ID = "S001";
            else
            {
                int temp = 0;
                foreach (var i in query)
                    temp = int.Parse(i.ToString().Substring(2)) + 1;
                if (temp < 10)
                    ID = "S00" + temp.ToString();
                else if (temp < 100)
                    ID = "S0" + temp.ToString();
                else
                    ID = "S" + temp.ToString();
            }
            return ID;
        }

        /// <summary>
        /// This method is used o getManufacturerID
        /// </summary>
        /// <returns>ManufacturerID</returns>
        private string getManufacturerID()
        {
            string ID = "";

            var query = from i in db.Manufacrurers
                        select i.ManufacrurerID;

            if (query.Count() == 0)
                ID = "M001";
            else
            {
                int temp = 0;
                foreach (var i in query)
                    temp = int.Parse(i.ToString().Substring(2)) + 1;
                if (temp < 10)
                    ID = "M00" + temp.ToString();
                else if (temp < 100)
                    ID = "M0" + temp.ToString();
                else
                    ID = "M" + temp.ToString();
            }
            return ID;
        }

        /// <summary>
        /// This method is used to getSupplierID
        /// </summary>
        /// <returns>SupplierID</returns>
        private string getSupplierID()
        {
            string ID = "";

            var query = from i in db.Suppliers
                        select i.SupplierID;

            if (query.Count() == 0)
                ID = "NPP00001";
            else
            {
                int temp = 0;
                foreach (var i in query)
                    temp = int.Parse(i.ToString().Substring(3)) + 1;
                if (temp < 10)
                    ID = "NPP0000" + temp.ToString();
                else if (temp < 100)
                    ID = "NPP000" + temp.ToString();
                else if (temp < 1000)
                    ID = "NPP00" + temp.ToString();
                else if (temp < 10000)
                    ID = "NPP0" + temp.ToString();
                else
                    ID = "NPP" + temp.ToString();
            }
            return ID;
        }
        private Utility util;

        /// <summary>
        /// This method is used to CheckTxtTheNho
        /// </summary>
        /// <returns></returns>
        private bool CheckTxtTheNho()
        {
            if (string.IsNullOrEmpty(txtTheNho.Text))
                return false;
            else
                return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgThem_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (chbCamera.IsChecked == true)
            {
                var T = from t in db.CameraDetails
                        where t.MegaPixel == txtCamera.Text
                        select t
                        ;
                if (T.Count() == 0)
                {
                    CameraDetail newCameraDetail = new CameraDetail();
                    newCameraDetail.CameraDetailID = getCameraDetailID();
                    newCameraDetail.MegaPixel = txtCamera.Text;
                    db.CameraDetails.InsertOnSubmit(newCameraDetail);
                    db.SubmitChanges();
                    var query = from t in db.CameraDetails
                                select t.MegaPixel;
                    util = new Utility();
                    util.ClearCombobox(cbCamera);
                    foreach (var item in query)
                    {
                        cbCamera.Items.Add(item);
                    }
                    MessageBox.Show("Đã thêm Camera thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbCamera.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Đã tồn tại loại camera này.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            if (chbTheNho.IsChecked == true)
            {
                var T = from t in db.MemoryCards
                        where t.Size == txtTheNho.Text
                        select t;

                if (T.Count() == 0)
                {
                    MemoryCard newMemoryCard = new MemoryCard();
                    newMemoryCard.MemoryCardID = getMemoryCardID();
                    newMemoryCard.Size = txtTheNho.Text;
                    db.MemoryCards.InsertOnSubmit(newMemoryCard);
                    db.SubmitChanges();
                    var query = from t in db.MemoryCards
                                select t.Size;
                    util = new Utility();
                    util.ClearCombobox(cbTheNho);
                    foreach (var item in query)
                    {
                        cbTheNho.Items.Add(item);
                    }
                    MessageBox.Show("Đã thêm Thẻ nhớ thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbTheNho.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Đã tồn tại loại thẻ nhớ này.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);

            }
            if (chbSim.IsChecked == true)
            {
                if (CheckTxtTheNho() == true)
                {
                    var T = from t in db.MultiSims
                            where t.SimQuantity == int.Parse(txtSoSim.Text)
                            select t;
                    if (T.Count() == 0)
                    {
                        MultiSim newMultiSim = new MultiSim();
                        newMultiSim.MultiSimID = getSimID();
                        try
                        {
                            newMultiSim.SimQuantity = int.Parse(txtSoSim.Text);
                        }
                        catch
                        {
                            MessageBox.Show("Chỉ được nhập số.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        db.MultiSims.InsertOnSubmit(newMultiSim);
                        db.SubmitChanges();
                        var query = from t in db.MultiSims
                                    select t.SimQuantity;
                        util = new Utility();
                        util.ClearCombobox(cbSim);
                        foreach (var item in query)
                        {
                            cbSim.Items.Add(item);
                        }
                        MessageBox.Show("Đã thêm số SIM hỗ trợ thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                        cbSim.SelectedIndex = 0;
                    }
                    else
                    {
                        MessageBox.Show("Đã tồn tại loại SIM hỗ trợ này.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                else
                {
                    MessageBox.Show("Ô Sim không được để trống.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            if (chbNhaSanXuat.IsChecked == true)
            {
                var T = from t in db.Manufacrurers
                        where t.ManufacrurerName == txtNhaSanXuat.Text
                        select t;
                if (T.Count() == 0)
                {
                    Manufacrurer newManufacturer = new Manufacrurer();
                    newManufacturer.ManufacrurerID = getManufacturerID();
                    newManufacturer.ManufacrurerName = txtNhaSanXuat.Text;
                    db.Manufacrurers.InsertOnSubmit(newManufacturer);
                    db.SubmitChanges();
                    var query = from t in db.Manufacrurers
                                select t.ManufacrurerName;
                    util = new Utility();
                    util.ClearCombobox(cbNhaSanXuat);
                    foreach (var item in query)
                    {
                        cbNhaSanXuat.Items.Add(item);
                    }
                    MessageBox.Show("Đã thêm nhà sản xuất thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbNhaSanXuat.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Đã tồn tại nhà sản xuất này.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            if (chbNhaPhanPhoi.IsChecked == true)
            {
                var T = from t in db.Suppliers
                        where t.Name == txtNhaPhanPhoi.Text
                        select t;
                if (T.Count() == 0)
                {
                    Supplier newSupplier = new Supplier();
                    newSupplier.SupplierID = getSupplierID();
                    newSupplier.Name = txtNhaPhanPhoi.Text;
                    db.Suppliers.InsertOnSubmit(newSupplier);
                    db.SubmitChanges();
                    var query = from t in db.Suppliers
                                select t.Name;
                    util = new Utility();
                    util.ClearCombobox(cbNhaPhanPhoi);
                    foreach (var item in query)
                    {
                        cbNhaPhanPhoi.Items.Add(item);
                    }
                    MessageBox.Show("Đã thêm nhà phân phối thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbNhaPhanPhoi.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Đã tồn tại nhà phân phối này.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }


        private void chbCamera_Checked(object sender, RoutedEventArgs e)
        {
            cbCamera.IsEnabled = true;
            txtCamera.IsEnabled = true;
        }

        private void chbCamera_Unchecked(object sender, RoutedEventArgs e)
        {
            cbCamera.IsEnabled = false;
            txtCamera.IsEnabled = false;
        }

        private void chbTheNho_Checked(object sender, RoutedEventArgs e)
        {
            cbTheNho.IsEnabled = true;
            txtTheNho.IsEnabled = true;
        }

        private void chbTheNho_Unchecked(object sender, RoutedEventArgs e)
        {
            cbTheNho.IsEnabled = false;
            txtTheNho.IsEnabled = false;
        }

        private void chbSim_Checked(object sender, RoutedEventArgs e)
        {
            cbSim.IsEnabled = true;
            txtSoSim.IsEnabled = true;
        }

        private void chbSim_Unchecked(object sender, RoutedEventArgs e)
        {
            cbSim.IsEnabled = false;
            txtSoSim.IsEnabled = false;
        }

        private void chbNhaSanXuat_Checked(object sender, RoutedEventArgs e)
        {
            cbNhaSanXuat.IsEnabled = true;
            txtNhaSanXuat.IsEnabled = true;
        }

        private void chbNhaSanXuat_Unchecked(object sender, RoutedEventArgs e)
        {
            cbNhaSanXuat.IsEnabled = false;
            txtNhaSanXuat.IsEnabled = false;
        }

        private void chbNhaPhanPhoi_Checked(object sender, RoutedEventArgs e)
        {
            cbNhaPhanPhoi.IsEnabled = true;
            txtNhaPhanPhoi.IsEnabled = true;
        }

        private void chbNhaPhanPhoi_Unchecked(object sender, RoutedEventArgs e)
        {
            cbNhaPhanPhoi.IsEnabled = false;
            txtNhaPhanPhoi.IsEnabled = false;
        }

        private void imgSua_MouseDown(object sender, MouseButtonEventArgs e)
        {

            if (chbCamera.IsChecked == true)
            {
                var T = from t in db.CameraDetails
                        where t.MegaPixel == txtCamera.Text
                        select t
                    ;
                if (T.Count() == 0)
                {
                    CameraDetail existCamera = (from t in db.CameraDetails
                                                where t.MegaPixel == cbCamera.SelectedItem.ToString()
                                                select t).Single();
                    existCamera.MegaPixel = txtCamera.Text;
                    db.SubmitChanges();
                    var query = from t in db.CameraDetails
                                select t.MegaPixel;
                    util = new Utility();
                    util.ClearCombobox(cbCamera);
                    foreach (var item in query)
                    {
                        cbCamera.Items.Add(item);
                    }
                    MessageBox.Show("Đã sửa Camera thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbCamera.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Đã tồn tại loại thẻ nhớ này", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
            }


            if (chbTheNho.IsChecked == true)
            {

                var T = from t in db.MemoryCards
                        where t.Size == txtTheNho.Text
                        select t;
                ;
                if (T.Count() == 0)
                {
                    MemoryCard existMemoryCard = (from t in db.MemoryCards

                                                  where t.Size == cbTheNho.SelectedItem.ToString()
                                                  select t).Single();
                    existMemoryCard.Size = txtTheNho.Text;
                    db.SubmitChanges();
                    var query = from t in db.MemoryCards
                                select t.Size;
                    util = new Utility();
                    util.ClearCombobox(cbTheNho);
                    foreach (var item in query)
                    {
                        cbTheNho.Items.Add(item);
                    }
                    MessageBox.Show("Đã sửa Thẻ nhớ thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbTheNho.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Loại thẻ này đã tồn tại.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);

            }
            if (chbSim.IsChecked == true)
            {
                var T = from t in db.MultiSims
                        where t.SimQuantity == int.Parse(txtSoSim.Text)
                        select t;
                if (T.Count() == 0)
                {
                    MultiSim existSim = (from t in db.MultiSims

                                         where t.SimQuantity.ToString() == cbSim.SelectedItem.ToString()
                                         select t).Single();
                    try
                    {
                        existSim.SimQuantity = int.Parse(txtSoSim.Text);
                    }
                    catch
                    {
                        MessageBox.Show("SIM hỗ trợ chỉ được nhập số.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    db.SubmitChanges();
                    var query = from t in db.MultiSims
                                select t.SimQuantity;
                    util = new Utility();
                    util.ClearCombobox(cbSim);
                    foreach (var item in query)
                    {
                        cbSim.Items.Add(item);
                    }
                    MessageBox.Show("Đã sửa số SIM hỗ trợ thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbSim.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Đã tồn tại số SIM hỗ trợ này.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            if (chbNhaSanXuat.IsChecked == true)
            {

                var T = from t in db.Manufacrurers
                        where t.ManufacrurerName == txtNhaSanXuat.Text
                        select t;
                ;
                if (T.Count() == 0)
                {
                    Manufacrurer existManufacturer = (from t in db.Manufacrurers

                                                      where t.ManufacrurerName == cbNhaSanXuat.SelectedItem.ToString()
                                                      select t).Single();
                    existManufacturer.ManufacrurerName = txtNhaSanXuat.Text;
                    db.SubmitChanges();
                    var query = from t in db.Manufacrurers
                                select t.ManufacrurerName;
                    util = new Utility();
                    util.ClearCombobox(cbNhaSanXuat);
                    foreach (var item in query)
                    {
                        cbNhaSanXuat.Items.Add(item);
                    }
                    MessageBox.Show("Đã sửa nhà sản xuất thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbNhaSanXuat.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Nhà sản xuất này đã tồn tại.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);

            }
            if (chbNhaPhanPhoi.IsChecked == true)
            {

                var T = from t in db.Suppliers
                        where t.Name == txtNhaPhanPhoi.Text
                        select t;
                ;
                if (T.Count() == 0)
                {
                    Supplier existSupplier = (from t in db.Suppliers

                                              where t.Name == cbNhaPhanPhoi.SelectedItem.ToString()
                                              select t).Single();
                    existSupplier.Name = txtNhaPhanPhoi.Text;
                    db.SubmitChanges();
                    var query = from t in db.Suppliers
                                select t.Name;
                    util = new Utility();
                    util.ClearCombobox(cbNhaPhanPhoi);
                    foreach (var item in query)
                    {
                        cbNhaPhanPhoi.Items.Add(item);
                    }
                    MessageBox.Show("Đã sửa nhà phân phối thành công.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    cbNhaPhanPhoi.SelectedIndex = 0;
                }
                else
                    MessageBox.Show("Nhà phân phối này đã tồn tại.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);

            }
        }

        private void btExit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void btAccessoryDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dgAccessory.SelectedItem != null)
            {
                Accessory selectedAccessory = dgAccessory.SelectedItem as Accessory;
                if (selectedAccessory.Product.Quantity != 0)
                    MessageBox.Show("Sản phẩm hiện vẫn còn, chưa thể xóa được.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                else
                {
                    ManagerController.Instance.InvokeDeleteAccessory(selectedAccessory);
                    MessageBox.Show("Sản phẩm hiện đã xóa.", "Thông tin", MessageBoxButton.OK, MessageBoxImage.Information);
                    Utility u = new Utility();
                    u.Manager_getAccessoryDataGrid(dgAccessory);
                }
            }
        }
	}

}
